package com.shyt.security;

import com.alibaba.fastjson.JSON;
import com.shyt.util.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


/****
 * 权限认证接口，返回权限错误信息
 */
@Component
@Slf4j
@ConfigurationProperties(prefix = "encoder.crypt")
public class AccessRejectUtil implements AccessDeniedHandler {
    /**
     * 加密强度
     */
    private int strength;
    /**
     * 干扰因子
     */
    private String secret;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {

        //System.out.println("secret = " + secret);
        //对干扰因子加密
        //SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        //对密码加密
        //return new BCryptPasswordEncoder(strength, secureRandom);
        return new BCryptPasswordEncoder();
    }

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        log.info("进入权限认证,验证开始__________________________________");
        String result = JSON.toJSONString(
                ApiResponse.erro("409", "权限认证失败", "权限认证不通过，请联系管理员")
        );

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        outputStream.write(result.getBytes(StandardCharsets.UTF_8));


        //outputStream.write("权限认证不通过，请联系管理员".getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
        log.info("进入权限结束,验证开始__________________________________");
    }
}
